/**
 * Created by Administrator on 2018/10/18.
 */

var user = getUser();
console.log(user);

// 格式化责任人
function dutyFormatter(value, row, index) {
    // console.log(value);
    if (value === '1') {
        return '<a class="btn-set" href="javascript:void(0);">未设置</a >';
    } else if (value === '0') {
        return '<span></span>';
    } else {
        // return '<span class="">' + value + '</span>';
        return '<a class="btn-set" href="javascript:void(0);">' + value + '</a>';
    }
}

// 格式化时间
function dateFormatter(value, row, index) {
    return value ? value : '';
}



// 检测对象类型
function type(obj) {
    return Object.prototype.toString.call(obj).replace(/\[object (\w+)\]/,'$1').toLowerCase();
}

function getProjectId(src) {
    console.log(src);
    var qs = src.split('?')[1];
    var args = {};
    var items = qs.length ? qs.split('&') : [];
    var len = items.length;
    if (qs.length == 0) {
        // alert("没有查询字符串,退出！");
        return;
    }
    for (var i = 0; i < len; i++) {
        var item = items[i].split("=");
        args[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
    }
    return args['taskId'];
}

$(function () {
    //Initialize Select2 Elements

});

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'generator/projectentity/list',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'id', index: 'id', width: 50, key: true },
            { label: '模板id', name: 'templateId', index: 'template_id', width: 80 },
            { label: '项目名', name: 'projectName', index: 'project_name', width: 80 },
            { label: '项目编号', name: 'projectNumber', index: 'project_number', width: 80 },
            { label: '项目所属区域', name: 'projectArea', index: 'project_area', width: 80 },
            { label: '项目类型', name: 'projectType', index: 'project_type', width: 80 },
            { label: '项目申请方', name: 'projectApplicant', index: 'project_applicant', width: 80 },
            { label: '申报时间', name: 'projectTime', index: 'project_time', width: 80 },
            { label: '申报时间', name: 'projectStartTime', index: 'project_start_time', width: 80 },
            { label: '项目描述', name: 'projectDescribe', index: 'project_describe', width: 80 },
            { label: '状态', name: 'projectStatus', index: 'project_status', width: 80 },
            { label: '开始时间', name: 'startTime', index: 'start_time', width: 80 },
            { label: '结束时间', name: 'endTime', index: 'end_time', width: 80 },
            { label: '电压类型', name: 'voltageType', index: 'voltage_type', width: 80 },
            { label: '项目级别', name: 'projectLevel', index: 'project_level', width: 80 },
            { label: '项目经理', name: 'projectManager', index: 'project_manager', width: 80 }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });

    $('#dropdownMenu2').on('click', function () {
        var oBtn = $(this);
        $('#template').on('click', 'li', function () {
            var oLi = $(this);
            oBtn.text(oLi.text()).attr('data-id',oLi.attr('data-id'));
            $('#inp-template').val(oLi.attr('data-id'));
        })
    });
    var newDate = new Date();
    var t = newDate.toJSON();
    // 时间控件
    $('#inp-date-start').datetimepicker({
        language:'zh-CN',
        format: 'yyyy-mm-dd',
        todayHighlight:1,
        showMeridian: 0,
        autoclose: 1,
        minView: 2
    });
    // 时间控件2
    $('#inp-start-date').datetimepicker({
        language:'zh-CN',
        format: 'yyyy-mm-dd',
        todayHighlight:1,
        showMeridian: 0,
        autoclose: 1,
        minView: 2,
        endDate : new Date()
    }).on('changeDate',function(ev){
        console.log(ev);
        console.log($('#inp-start-date').val());
        vm.projectEntity.projectStartTime = $('#inp-start-date').val();
        console.log(vm.projectEntity.projectStartTime);
    });

    // 表单验证规则
    $('#np-form').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {/*输入框不同状态，显示图片的样式*/
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {/*验证*/
            projectName: {/*键名username和input name值对应*/
                message: '项目名称校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '项目名称不能为空'
                    },
                    stringLength: {
                        max: 100,
                        message: '输入超出长度'
                    }
                }
            },
            projectNumber: {/*键名username和input name值对应*/
                message: '项目编号校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '项目编号不能为空'
                    },
                    stringLength: {
                        max: 64,
                        message: '输入超出长度'
                    }
                }
            },
            projectArea: {/*键名username和input name值对应*/
                message: '项目所属区域校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '项目所属区域不能为空'
                    },
                    stringLength: {
                        max: 32,
                        message: '输入超出长度'
                    }
                }
            },
            voltageType: {/*键名username和input name值对应*/
                message: '电压类型校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '电压类型不能为空'
                    },
                    stringLength: {
                        max: 32,
                        message: '输入超出长度'
                    }
                }
            },
            projectApplicant: {/*键名username和input name值对应*/
                message: '项目申请方校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '项目申请方不能为空'
                    }
                }
            },
            projectTime: {/*键名username和input name值对应*/
                message: '申报时间校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '申报时间不能为空'
                    }
                }
            },
            projectStartTime: {/*键名username和input name值对应*/
                message: '开始时间校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '开始时间不能为空'
                    }
                }
            },
            projectType: {/*键名username和input name值对应*/
                message: '项目类型校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '项目类型不能为空'
                    }
                }
            },
            projectLevel: {/*键名username和input name值对应*/
                message: '项目级别校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '项目级别不能为空'
                    }
                }
            },
            projectDescribe: {/*键名username和input name值对应*/
                message: '项目描述校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '项目描述不能为空'
                    },
                    stringLength: {
                        max: 300,
                        message: '输入超出长度'
                    }
                }
            },
            templateId: {/*键名username和input name值对应*/
                message: '模板名称校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '模板名不能为空'
                    }
                }
            }
        }
    });

});

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        projectEntity: {
            voltageType:''
        },
        areaList: [],   // 项目所属区域列表
        vTypeList: [],  // 电压类型列表
        pTypeList: [],  // 项目类型列表
        applicantList: [],  // 项目申请方
        mTypeList: [],  // 项目流程模板列表
        pLevelList: [], // 项目级别列表
        pmList: [], // 项目经理列表
        projectId: '',
        projectName:'',
        projectApplicantList:[]
    },
    mounted: function () {
        // console.log(this.showList);
        var _this = this;
        var user = getUser();
        console.log(user);
        var myDate = new Date();
        var time = myDate.toLocaleDateString().split('/').join('-');
        _this.projectEntity.projectTime = time;
        _this.projectEntity.projectStartTime = time;

        /* 项目经理列表 */
        $.get(baseURL+'sys/user/listpm', function (result) {
            console.log(result);
            var list = result.pmList;
            var tempList = [];
            for (var i = 0; i < list.length; i++) {
                var temp = {
                    pmName: list[i].name,
                    pmId: list[i].userId
                };
                tempList.push(temp);
            }
            _this.pmList = tempList;
            var index = 0;
            for (var i = 0 ; i<tempList.length;i++){
                if (tempList[i].pmId == user.userId) {
                    index = i;
                }
            }
            _this.projectEntity.projectManager = _this.pmList[index].pmId;
        });

        /* 项目申请方列表 */
        $.get(baseURL+'generator/projectapplicantinfo/alllist', function (result) {
             console.log(result);
            _this.projectApplicantList = result.applicantList;
            _this.projectEntity.projectApplicant = _this.projectApplicantList[0].id;
            //项目申请方
            $('#projectApplicant').select2({
                data: result.applicantList,
                placeholder:'请选择项目申请方',//默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                multiple: false
            });
            $("#projectApplicant").val("").select2();

        });

        //相关线路的列表
        $.get(baseURL+'generator/projectlineinfo/listAll', function (result) {
            console.log(result);
            $('#line').select2({
                data: result.projectLineInfoList,
                placeholder:'请选择相关线路',//默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                multiple: true, //启用多选
                tags:true,
                createTag: function(params) {//解决部分浏览器开启 tags: true 后无法输入中文的BUG
                    if (/[;]/.test(params.term)) {
                        var str = params.term.trim().replace(/[;]*$/, '');
                        return { id: str , text: str }
                    }
                }
            });
        });
        //输入内容后生成按回车键即可
        $(document).on('keyup', '.select2-selection--multiple .select2-search__field', function(event){
            if(event.keyCode == 13){//这个是回车键的键值，如果要按其他键，把键值换成其他键值就可以了
                var $this = $(this);
                var optionText = $this.val();//输入内容的value值
                //如果没有就添加
                if(optionText != "" && $this.find("option[value='" + optionText + "']").length === 0){
                    //我还不知道怎么优雅的定位到input对应的select
                    var $select = $this.parents('.select2-container').prev("select");
                    var newOption = new Option( optionText,optionText, true, true);//定义一个新的option,设置option的值是输入框的内容
                    $select.append(newOption).trigger('change');//在插入的时候同时生成标签
                    $this.val('');//清空输入框的内容
                }
            }
        });

        $.get(baseURL+'generator/basetemplate/query', function (result) {
            _this.mTypeList = result.list;
            _this.projectEntity.templateId = _this.mTypeList[0].id;

        });
        this.areaList = [
            {
                id: 10001,
                text: '武昌区'
            },
            {
                id: 10002,
                text: '汉口区'
            },
            {
                id: 10003,
                text: '汉阳区'
            },
            {
                id: 10004,
                text: '东新区'
            },
            {
                id: 10005,
                text: '沌口区'
            },
            {
                id: 10006,
                text: '东西湖区'
            },
            {
                id: 10007,
                text: '黄陂区'
            },
            {
                id: 10008,
                text: '新洲区'
            },
            {
                id: 10009,
                text: '汉南区'
            },
            {
                id: 10010,
                text: '江夏区'
            },
            {
                id: 10011,
                text: '蔡甸区'
            }
        ];

        //项目所属区域
        $('#applicant').select2({
            data: this.areaList,
            placeholder:'请选择项目所属区域',//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            multiple: true
           /* multiple: false, //启用多选
            maximumSelectionSize:1*/
        });


        this.vTypeList = [
            {
                typeCode: 1,
                typeName: '中压'
            },
            {
                typeCode: 2,
                typeName: '高压'
            }
        ];
        this.projectEntity.voltageType = this.vTypeList[0].typeCode;

        this.pTypeList = [
            {
                typeCode: 1,
                typeName: '输电'
            },
            {
                typeCode: 2,
                typeName: '配电'
            }
        ];
        this.projectEntity.projectType = this.pTypeList[0].typeCode;

        this.pLevelList = [
            {
                levelCode: 1,
                levelName: '紧急'
            },
            {
                levelCode: 2,
                levelName: '重要'
            },
            {
                levelCode: 3,
                levelName: '一般'
            }
        ];
        this.projectEntity.projectLevel = this.pLevelList[0].levelCode;
    },
    watch: {
        'projectEntity.voltageType': function(val,newval){
            console.log(newval);
            if (newval == 1){
                vm.projectEntity.projectType = 1;
            }else {
                vm.projectEntity.projectType = 2;
            }
        },
        'projectEntity.projectTime' : function (val,newval) {
            console.log(val);
            console.log(newval);
            vm.projectEntity.projectTime = newval;
        },
        'projectEntity.projectStartTime' : function (val,newval) {
            console.log(val);
            console.log(newval);
            vm.projectEntity.projectStartTime = newval;
        }
    },
    methods: {
        /*getProjectType:function(){

        },*/
        inputFunc: function () {
            console.log(this);
            console.log('值变了');
            console.log(this.$refs.input1.value);
            console.log($('#inp-date-start').val());
            this.projectEntity.projectTime = this.$refs.input1.value;
        },
        inputStartDateFunc: function () {
            console.log(this);
            console.log('值变了');
            console.log(this.$refs.input2.value);
            console.log($('#inp-start-date').val());
            this.projectEntity.projectStartTime = this.$refs.input2.value;
        },
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = true;
            vm.title = "新增";
            vm.projectEntity = {};
        },
        update: function (event) {
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            var lineList = []; //相关线路集合
            var lineNameList = [];
            var applicantList = []; //项目所属区域集合
            var projectApplicant = null; //项目申请方字段
            var _this = this;
            var bootstrapValidator = $("#np-form").data('bootstrapValidator');
            bootstrapValidator.validate();
            console.log(bootstrapValidator.isValid());
            if(!bootstrapValidator.isValid()) {
                console.log('验证不通过');
                alert('请输入合法值');
                return false;
            } else {
                //相关线路
                     lineList=$("#line").val();    //多选
                for (var i = 0; i < $("#line").select2("data").length; i++) {
                    lineNameList.push($("#line").select2("data")[i].text)
                }
                if (lineList!= null && lineNameList.length != 0){
                    vm.projectEntity.relevantLinesName = lineNameList.join(',');
                };
                if (lineList!= null && lineList.length != 0){
                    vm.projectEntity.lineList = lineList.join(',');
                };
                //项目所属区域
                applicantList = $("#applicant").val();
                if (applicantList != null && applicantList.length != 0){
                    vm.projectEntity.projectArea = applicantList.join(',');
                };
                //项目申请方
                projectApplicant = $("#projectApplicant").val();
                console.log(projectApplicant);
                if (projectApplicant != null && projectApplicant != ''){
                    vm.projectEntity.projectApplicant = projectApplicant;
                }else {
                    alert("项目申请方为空！");
                    return false;
                };

                vm.projectEntity.projectTime = $('#inp-date-start').val();
                console.log(vm.projectEntity);
                var url = vm.projectEntity.id == null ? "generator/projectentity/save" : "generator/projectentity/update";
                vm.projectEntity.projectStatus = 0; // 0：进展中，1：已完成，2：已超期
                vm.projectEntity.createUser = user.userId;
                console.log(user.userId);
                $.ajax({
                    async : false,
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.projectEntity),
                    success: function(r){
                        console.log(r);
                        if (r.msg === "0101") {
                            alert("该项目编号已存在");
                            return false;
                        }
                        console.log(r.projectName);
                        _this.projectId = r.projectId;
                        _this.projectName = r.projectName;
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                _this.showList = false;
                            });
                            /*绑定设置负责人事件*/
                            var operateEvents = {
                                "click .btn-set": function (e, value, row, index) {
                                    console.log($(this));
                                    var taskId = row.id;    // 任务Id
                                    var oBtn = $(this);

                                    $.ajax({
                                        type: 'POST',
                                        url: baseURL + 'sys/user/getUpPerson',
                                        success: function (result) {
                                            var deptList = result.userList;
                                            var treeData = [];
                                            for (var i = 0; i < deptList.length; i++) {
                                                var temp = {
                                                    deptId: deptList[i].deptId,
                                                    text: deptList[i].deptName
                                                };
                                                var userList = deptList[i].userList;
                                                if (userList.length > 0) {
                                                    var users = [];
                                                    for (var j = 0; j < userList.length; j++) {
                                                        var tempUser = {
                                                            deptId: userList[j].deptId,
                                                            id: userList[j].id,
                                                            text: userList[j].userName
                                                        };
                                                        users.push(tempUser);
                                                    }
                                                    temp.nodes = users;
                                                }
                                                treeData.push(temp);
                                            }
                                            console.log(treeData);

                                            /*var listHtml = '<div class="data-pane">' +
                                                '<div id="user-list"></div>' +
                                                '</div>'+
                                                '<div class="btn-pane">' +
                                                '<button type="button" class="btn btn-primary" id="btn-ensure">确定</button>' +
                                                '</div>';*/

                                            var listHtml = '<div class="btn-pane">' +
                                                '<button type="button" class="btn btn-primary" id="btn-ensure">确定</button>' +
                                                '</div>'+
                                                '<div class="data-pane">' +
                                                '<div id="user-list"></div>' +
                                                '</div>';

                                            layer.open({
                                                type: 1,
                                                skin: 'layui-layer-demo', //样式类名
                                                closeBtn: 1, //不显示关闭按钮
                                                anim: 2,
                                                area: ['400px', '500px'],
                                                shadeClose: true, //开启遮罩关闭
                                                content: listHtml
                                            });

                                            $('#user-list').treeview({
                                                levels: 1,
                                                data: treeData
                                            });

                                            $('#btn-ensure').on('click', function () {
                                                var user = $('#user-list').treeview('getSelected')[0];
                                                console.log(user);
                                                if (!user.id) {
                                                    return false;
                                                } else {
                                                    var postData = {id: taskId, taskRespDept: user.deptId,taskRespUser:user.id};
                                                    $.ajax({
                                                        type: 'POST',
                                                        url: baseURL + 'generator/pojecttask/update',
                                                        contentType: "application/json",
                                                        data: JSON.stringify(postData),
                                                        success: function (result) {
                                                            console.log(result);
                                                            oBtn.text(user.text);
                                                        }
                                                    });
                                                    layer.close(layer.index);
                                                }
                                            });
                                        }
                                    });
                                }
                            };

                            $.ajax({
                                async : false,
                                type:"POST",
                                url:baseURL + 'generator/pojecttask/milepost/' + _this.projectId,
                                success:function(data){
                                    var taskList = data.taskMap;
                                    var oTable = $('#stage-table');
                                    console.log(data.taskMap);
                                    var tableData = [];
                                    for (var i = 0; i < taskList.length; i++) {
                                        var id = parseInt(taskList[i].id);
                                        var pid = parseInt(taskList[i].pid);
                                        taskList[i].id = id;
                                        taskList[i].pid = pid;
                                        tableData.push(taskList[i]);
                                    }
                                    oTable.bootstrapTable({
                                        data: tableData,
                                        striped: false,
                                        //sidePagination: 'server',
                                        idField: 'id',
                                        columns: [
                                            {
                                                field: 'ck',
                                                checkbox: true
                                            },
                                            {
                                                field: 'name',
                                                title: '项目名称'
                                            },
                                            {
                                                field: 'startTime',
                                                align: 'center',
                                                title: '开始时间',
                                                formatter: 'dateFormatter'
                                            },
                                            {
                                                field: 'phase',
                                                align: 'center',
                                                title: '阶段类型'
                                            },
                                            {
                                                field: 'dutyPerson',
                                                title: '责任人',
                                                align: 'center',
                                                events: operateEvents,
                                                formatter: 'dutyFormatter'
                                            }
                                        ],
                                        treeShowField: 'name',
                                        parentIdField: 'pid',
                                        onResetView: function(data) {
                                            oTable.treegrid({
                                                initialState: 'collapsed',// 所有节点都折叠
                                                // initialState: 'expanded',// 所有节点都展开，默认展开
                                                treeColumn: 1,
                                                expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                                                expanderCollapsedClass: 'glyphicon glyphicon-plus',
                                                onChange: function() {
                                                    oTable.bootstrapTable('resetWidth');
                                                }
                                            });
                                            //只展开树形的第一级节点
                                            oTable.treegrid('getRootNodes').treegrid('expand');
                                        }
                                    });
                                }
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        del: function (event) {
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }

            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "generator/projectentity/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function(id){
            $.get(baseURL + "generator/projectentity/info/"+id, function(r){
                vm.projectEntity = r.projectEntity;
            });
        },
        goDetails: function (event) {
            console.log(event);
            var projectId = this.projectId;
            var data = {
                id:projectId
            };

            $.ajax({
                type: "POST",
                headers: {
                    token:token
                },
                url: baseURL + "generator/projectentity/taskPreservation",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(r){
                    if(r.code == 0){
                        alert('操作成功', function(index){
                            var pWindow = window.parent;
                            var oIframe = $('#main-content iframe', pWindow.document);
                            // console.log(oIframe);
                            oIframe.attr('src','modules/project/projectdetails.html?projectId=' + projectId);
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page
            }).trigger("reloadGrid");
        }
    }
});